//////////////////////////////////////////////////////////////////////////////////////
//
//  Copyright (c) 2014-present, Egret Technology.
//  All rights reserved.
//  Redistribution and use in source and binary forms, with or without
//  modification, are permitted provided that the following conditions are met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//     * Neither the name of the Egret nor the
//       names of its contributors may be used to endorse or promote products
//       derived from this software without specific prior written permission.
//
//  THIS SOFTWARE IS PROVIDED BY EGRET AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
//  OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
//  OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
//  IN NO EVENT SHALL EGRET AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
//  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
//  LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;LOSS OF USE, DATA,
//  OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
//  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
//  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
//  EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////////////////

class Main extends eui.UILayer {


    protected createChildren(): void {
        super.createChildren();

        egret.lifecycle.addLifecycleListener((context) => {
            // custom lifecycle plugin
        })

        egret.lifecycle.onPause = () => {
            egret.ticker.pause();
        }

        egret.lifecycle.onResume = () => {
            egret.ticker.resume();
        }

        //inject the custom material parser
        //注入自定义的素材解析器
        let assetAdapter = new AssetAdapter();
        egret.registerImplementation("eui.IAssetAdapter", assetAdapter);
        egret.registerImplementation("eui.IThemeAdapter", new ThemeAdapter());


        this.runGame().catch(e => {
            console.log(e);
        })
    }

    private async runGame() {
        await this.loadResource()
        this.createGameScene();
        const result = await RES.getResAsync("description_json")
        await platform.login();
        const userInfo = await platform.getUserInfo();
        console.log(userInfo);

    }

    private async loadResource() {

        try {
            await RES.loadConfig("resource/default.res.json", "resource/");
            await RES.loadGroup("loading", 1);
            const loadingView = new LoadingUI();
            this.stage.addChild(loadingView);
            await this.loadTheme();
            await RES.loadGroup("preload", 0, loadingView);
            this.stage.removeChild(loadingView);
        }
        catch (e) {
            // this.stage.removeChild(loadingView);
            console.error(e);
        }
    }

    private loadTheme() {
        return new Promise((resolve, reject) => {
            // load skin theme configuration file, you can manually modify the file. And replace the default skin.
            //加载皮肤主题配置文件,可以手动修改这个文件。替换默认皮肤。
            let theme = new eui.Theme("resource/default.thm.json", this.stage);
            theme.addEventListener(eui.UIEvent.COMPLETE, () => {
                resolve();
            }, this);

        })
    }

    private textfield: egret.TextField;
    /**
     * 创建场景界面
     * Create scene interface
     */
    protected createGameScene(): void {
        this.addChild(new ScreenLayer());
        // this.checkHit();
    }
    /**查询访问统计数 */
    public static hitNum: number = 0;
    private hitPath: string = "http://127.0.0.1:7001/miva_see_hit";
    private params = "name=两会";
    private checkHit() {
        const req = new egret.HttpRequest();
        req.responseType = egret.HttpResponseType.TEXT;
        req.open(this.hitPath, egret.HttpMethod.POST);
        req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        req.send(this.params);
        req.addEventListener(egret.Event.COMPLETE, (evt: egret.Event) => {
            const res = JSON.parse(evt.currentTarget.response);
            Main.hitNum = res.data.length;
            console.log(res, Main.hitNum);
        }, this);
    }
    /**搭配html页面的,截图分享 */
    public static shareImage(target: egret.DisplayObject): void {
        var renderTexture = new egret.RenderTexture();
        renderTexture.drawToTexture(target);//渲染到临时画布
        var divImage = document.getElementById("divImage");//获取DIV
        var shareImage: HTMLImageElement = document.getElementById("shareImage") as HTMLImageElement;//获取Image标签
        shareImage.src = renderTexture.toDataURL('image/jpeg');//把数据赋值给Image
        divImage.style.display = "block";//显示DIV
    }
    /**
     * 根据name关键字创建一个Bitmap对象。name属性请参考resources/resource.json配置文件的内容。
     * Create a Bitmap object according to name keyword.As for the property of name please refer to the configuration file of resources/resource.json.
     */
    public static createBitmapByName(name: string): egret.Bitmap {
        let result = new egret.Bitmap();
        let texture: egret.Texture = RES.getRes(name);
        result.texture = texture;
        return result;
    }
    /** 锚点居中, 传入一个显示对象, 设置它的锚点居中到自己正中心; */
    public static anchorCenter(item: any): void {
        item.anchorOffsetX = item.width / 2;
        item.anchorOffsetY = item.height / 2;
    }
    /**取消事件冒泡 */
    public static superStopPropagation(evt) {
        evt.stopPropagation();
        evt.stopImmediatePropagation();
    }
    /** 场景逻辑完毕 */
    public static screenComplete(params) {
        params.target.dispatchEvent(new egret.Event("next"));
    }
    /** 视图对象拖动获取坐标方法 */
    public static dragGetPatn(target: egret.DisplayObject, container, funObj?: { startFun?: Function, moveFun?: Function, endFun?: Function }, isDrag: boolean = true): void {
        /** 初始触摸点 */
        const startPoint: egret.Point = new egret.Point();
        const comput = new egret.Point();

        target.touchEnabled = true;
        target.addEventListener(egret.TouchEvent.TOUCH_BEGIN, touchBeginHandler, target);
        /** 开始触摸处理器 */
        function touchBeginHandler(evt) {
            startPoint.x = evt.stageX;
            startPoint.y = evt.stageY;
            target.addEventListener(egret.TouchEvent.TOUCH_MOVE, touchMoveHandler, target);
            target.addEventListener(egret.TouchEvent.TOUCH_END, touchEndHandler, target);

            container.setChildIndex(target, 99);
            /** 附加方法 */
            if (funObj && funObj.startFun) funObj.startFun(target, container);
        }
        /** 拖动处理器 */
        function touchMoveHandler(evt) {
            /** 附加方法 */
            if (funObj && funObj.moveFun) funObj.moveFun(target, container);
            /** 加入拖动开关, 默认开启拖动: 2019年3月11日 17:31:36 这里还有点小问题, 明天再改, 2019年3月12日 09:26:11 解决 */
            if (!isDrag) return;
            comput.x = evt.stageX - startPoint.x;
            comput.y = evt.stageY - startPoint.y;
            startPoint.x = evt.stageX;
            startPoint.y = evt.stageY;
            target.y += comput.y;
            target.x += comput.x;
        }
        /** 结束触摸处理器 */
        function touchEndHandler(evt) {
            console.log(target.x, target.y);
            target.removeEventListener(egret.TouchEvent.TOUCH_MOVE, touchMoveHandler, target);
            /** 附加方法 */
            if (funObj && funObj.endFun) funObj.endFun(target, container);
        }
    };
    /** 缩放添加视图对象 */
    public static createScale(target, container: egret.DisplayObjectContainer) {
        container.addChild(target);
        // target.scaleX = .5;
        // target.scaleY = .5;
    }
    /** 创建提示点 */
    public static createTipPoint(): egret.Sprite {
        const tipPoint = new egret.Sprite();
        tipPoint.graphics.beginFill(0xffffff, 1);
        tipPoint.graphics.drawCircle(0, 0, 10)
        tipPoint.graphics.endFill();
        tipPoint.graphics.beginFill(0xffffff, .3);
        tipPoint.graphics.drawCircle(0, 0, 20)
        tipPoint.graphics.endFill();
        tipPoint.graphics.lineStyle(3, 0xffffff);
        tipPoint.graphics.drawArc(0, 0, 20, 0, Math.PI / 180 * 60, true);
        tipPoint.graphics.endFill();

        egret.Tween.get(tipPoint, { loop: true })
            .to({ rotation: 180, scaleX: .5, scaleY: .5 }, 1000)
            .to({ rotation: 360, scaleX: 1, scaleY: 1 }, 1000);

        return tipPoint;
    }
    /** 道具提示动画 */
    public static itemAniamtion(target) {
        // Main.anchorCenter(target);
        egret.Tween.get(target, { loop: true })
            .to({ scaleX: target.scaleX * .8, scaleY: target.scaleY * .8 }, 500)
            .to({ scaleX: target.scaleX * 1.2, scaleY: target.scaleY * 1.2 }, 500)
            .to({ scaleX: target.scaleX, scaleY: target.scaleX }, 500)
            .wait(500)
            .to({ rotation: target.rotation + 10 }, 500)
            .to({ rotation: target.rotation + -10 }, 500)
            .to({ rotation: target.rotation + 10 }, 500)
            .to({ rotation: target.rotation + 0 }, 500)
            .wait(500)
    }
    /** 场景标题 */
    public static screenTitle(container, text?) {
        const txt = new egret.TextField();
        container.addChild(txt);
        txt.text = text || "场景标题";
    }
}
